﻿using YMJake.Flowable.ExternalWorker.Client.AspNetCore.Pipeline;
using YMJake.Flowable.ExternalWorker.Client.Core.Client;

namespace YMJake.Flowable.ExternalWorker.Client.Sample.Handlers;

/// <summary>
/// 通知处理器
/// </summary>
public class NotificationHandler : IWorkerHandler
{
    private readonly ILogger<NotificationHandler> _logger;

    public NotificationHandler(ILogger<NotificationHandler> logger)
    {
        _logger = logger;
    }

    public async Task HandleAsync(IWorkerPipelineContext context)
    {
        _logger.LogInformation("Sending notification for job {JobId}", context.Job.Id);

        var recipient = GetStringVariable(context.Job, "recipient", "unknown");
        var message = GetStringVariable(context.Job, "message");

        _logger.LogInformation("Sending to {Recipient}: {Message}", recipient, message);
        
        Console.WriteLine($"Console output - Sending to {recipient}: {message}");

        // 模拟发送
        await Task.Delay(500, context.CancellationToken);

        context.Result = context.ResultBuilder.Success()
            .Variable("sentAt", DateTime.UtcNow)
            .Variable("recipient", recipient)
            .Variable("status", "sent");
    }

    private string GetStringVariable(IAcquiredExternalWorkerJob job, string key, string defaultValue = "")
    {
        var value = job.Variables.GetValueOrDefault(key, defaultValue);
        return value?.ToString() ?? defaultValue;
    }
}